﻿using System;
using System.Windows;
using VideoRentalShop.View;
using VideoRentalShop.Model;
using System.Linq;
using System.Data.Entity;
using System.IO;
using System.Drawing;
using System.Windows.Media;

namespace VideoRentalShop.Controller
{
    public delegate void MessageClosedHandler(int id, MessageBoxResult result);


    public class VideoRentalShopController
    {
        private static readonly string PICTURE_PATH_FORMAT = "{0}{1} ({2}).{3}";
        private static readonly string PICTURE_NAME_FORMAT = "{0} ({1}).{2}";
        private Application _application;
        private Window _mainWindow;
        private string _baseDirectory;
        private string _imageBaseDirectory;
        private string _defaultPicture;
        private ImageSourceConverter _imageConverter;
        public ErrorReceiver ErrorReceiver { get { return ErrorReceiver.Instance; } }
        private DataSource _db;
        public DataSource Data {
            get
            {
                return _db;
            }
        }


        private VideoRentalShopController()
        {
            _application = Application.Current;
            _baseDirectory = App.ResourceAssembly.Location.Substring(0, App.ResourceAssembly.Location.LastIndexOf('\\') + 1);
            _imageBaseDirectory = _baseDirectory + "Images\\";
            _defaultPicture = _imageBaseDirectory + "noImage.png";
            CreateDirectories();
            _db = DataSource.Instance;

            _imageConverter = new ImageSourceConverter();
        }

        private static VideoRentalShopController _instance;
        public static VideoRentalShopController Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new VideoRentalShopController();
                }

                return _instance;
            }
        }


        private void CreateDirectories()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            if (!Directory.Exists(_imageBaseDirectory))
            {
                Directory.CreateDirectory(_imageBaseDirectory);
            }
        }

        public void StartUp()
        {
            Data.CleanDatabase();

            if (_mainWindow == null)
            {
                _mainWindow = new MainWindow();
                _application.MainWindow = _mainWindow;
            }
            _mainWindow.Show();
        }


        public ImageSource GetImage(string name)
        {
            var file = _imageBaseDirectory + name;
            if (!File.Exists(file))
            {
                file = _defaultPicture;
            }

            try
            {
                return _imageConverter.ConvertFromString(file) as ImageSource;
            }
            catch { }

            return null;
        }

        public string SavePicture(string path)
        {
            if (!File.Exists(path))
            {
                return null;
            }

            var idx = path.LastIndexOf('\\');
            var name = path.Substring(idx + 1);
            var newFile = _imageBaseDirectory + name;
            var copiable = false;
            if (File.Exists(newFile))
            {
                idx = name.LastIndexOf('.');
                var justName = name.Substring(0, idx);
                var extension = name.Substring(idx + 1);

                for (long i = 0; i < long.MaxValue; ++i)
                {
                    var newName = string.Format(PICTURE_PATH_FORMAT, _imageBaseDirectory, justName, i, extension);
                    if (!File.Exists(newName))
                    {
                        copiable = true;
                        newFile = newName;
                        name = string.Format(PICTURE_NAME_FORMAT, justName, i, extension);
                        break;
                    }
                }
            }
            else
            {
                copiable = true;
            }

            if (copiable)
            {
                try
                {
                    File.Copy(path, newFile);
                }
                catch (Exception e)
                {
                    ErrorReceiver.Catched(e);
                    copiable = false;
                }
            }

            if (!copiable)
            {
                ShowMessage(string.Format("Nie udało się zapisać obrazka o nazwie '{0}'.", name), "Błąd", MessageType.Error);
                newFile = null;
            }
            return name;
        }


        public MessageBoxResult ShowMessage(string message, MessageType type = MessageType.Info, MessageClosedHandler closedHandler = null, int id = 0)
        {
            var result = MessageBox.Show(message);

            if (closedHandler != null)
            {
                closedHandler(id, result);
            }

            return result;
        }

        public MessageBoxResult ShowMessage(string message, string title, MessageType type = MessageType.Info, MessageClosedHandler closedHandler = null, int id = 0)
        {
            var result = MessageBox.Show(message, title);

            if (closedHandler != null)
            {
                closedHandler(id, result);
            }

            return result;
        }
    }
}
